package com.jdiv.internalClasses;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;

import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.jdiv.JDiv;


public class TextManager {

	FNTManager manager;
	
	Map<Integer, List<Character>> fuentes;

	public List<WriteText> writeTextList;
	
	int cntrFuentes = 0;
	
	public TextManager() {
		manager = new FNTManager();
		writeTextList = new ArrayList<WriteText>();
		fuentes = new TreeMap<Integer, List<Character>>();
	}
	
	public int loadFnt(String path) {
		
		List<Character> list = manager.tratarFuente(path);
		
		fuentes.put(cntrFuentes, list);
		int id = cntrFuentes;
		cntrFuentes++;
		return id;
		
	}
	
	public void writeAllText(SpriteBatch batch) {
		
		for (int i = 0; i < writeTextList.size(); i++) {
			WriteText wt = writeTextList.get(i);
			writeInBatch(batch, wt.fontId, wt.x, wt.y, wt.cadena);
			writeTextList.remove(i);
		}
		
	}
	
	public void writeInBatch(SpriteBatch batch, int idFuente, int x, int y, String cadena){
		
		if (batch != null) {
			int fontHeight = 0;
			List<Character> caracteres = fuentes.get(idFuente);
			if (caracteres != null) {
				int xPos = x;
				int yPos = y;
				for (int i = 0; i < cadena.length(); i++) {
					int code = cadena.codePointAt(i);
					if (code != 32) {
						Character ch = caracteres.get(code);
						if (ch.region == null)
							ch.createRegion();
						if (fontHeight == 0)
							fontHeight=ch.region.getRegionHeight();
						batch.draw(ch.region, xPos, yPos - fontHeight, ch.width, ch.height);

						xPos+=ch.width;
					} else {
						xPos += 10;
					}
					
				}
			} 
			
		} 
		
	}
	
	public int write (int idFuente, int x, int y, int alignment, String cadena) {
		this.writeTextList.add(new WriteText(idFuente, x, JDiv.screen.getHeight() - y, alignment, cadena));
		return this.writeTextList.size();
	}

	public int write (int idFuente, int x, int y, int alignment, int variable) {
		return this.write(idFuente, x, y, alignment, Integer.toString(variable));
	}

	public int write (int idFuente, int x, int y, int alignment, float variable) {
		return this.write(idFuente, x, y, alignment, Float.toString(variable));
	}
	
	public void deleteText(int textId) {
		if (textId == 0)
			this.writeTextList.clear();
		else
			this.writeTextList.remove(textId);
	}

	public void init() {
		
		System.out.println("Init bennu fonts.");
		Set<Integer> set = this.fuentes.keySet();
		
		Iterator<Integer> it = set.iterator();
		
		while (it.hasNext()) {
			int fontId = it.next();
			System.out.println("Init font id " + fontId);
			List<Character> list = this.fuentes.get(fontId);
			for (int i = 0; i < list.size(); i++) {
				list.get(i).createRegion();
			}
			
		}
	}
	
}
